﻿import type { App } from 'vue'
import { createWebHashHistory, createRouter } from 'vue-router'
import { routerWhiteList, setPageTitle } from './utils/public'
import { cloneDeep, split } from 'lodash-es'
import { initRouter } from './utils/dataOperate'
import { getConstantRoutes } from './utils/routeOperate'
import { openLink } from '@/utils'
import { useUserStoreWithOut } from '@/store/modules/user'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useMenuStoreWithOut } from '@/store/modules/menu'
import { useTagCacheStoreWithOut } from '@/store/modules/tag'
import { useKeepAliveStoreWithOut } from '@/store/modules/keepAlive'
import { storeToRefs } from 'pinia'
import remainingRouter from './remaining'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
const { VITE_PUBLIC_PATH, VITE_ELECTRON } = import.meta.env
const tagCacheStore = useTagCacheStoreWithOut()
const menuStore = useMenuStoreWithOut()
const keepAliveStore = useKeepAliveStoreWithOut()
const userStore = useUserStoreWithOut()
const appStore = useAppStoreWithOut()

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

// 创建路由实例
export const router = createRouter({
  history: createWebHashHistory(VITE_PUBLIC_PATH),
  routes: getConstantRoutes()
})

router.beforeEach((to, _from, next) => {
  userStore.getUserInfoCache()
  tagCacheStore.getAllTagCache()
  tagCacheStore.getFixedTagCache()
  // 获取被缓存的标签页数据
  const { tagList } = storeToRefs(tagCacheStore)
  const { systemConfig } = storeToRefs(appStore)
  const { menuList } = storeToRefs(menuStore)
  const { scrollPosition } = storeToRefs(keepAliveStore)
  const { userInfo } = storeToRefs(userStore)
  // 标签栏刷新按钮清除保留的滚动记录
  if (_from.name === 'redirect') {
    keepAliveStore.removeScrollPosition({ path: '/' + _from.params.path })
  }
  // 添加页面状态缓存
  if (systemConfig.value && systemConfig.value.isKeepAlive && to.meta?.keepAlive) {
    const newMatched = to.matched
    keepAliveStore.handleAliveRoute(newMatched, 'add')
    // 页面整体刷新和点击标签页刷新
    if (_from.name === undefined || _from.name === 'redirect') {
      keepAliveStore.handleAliveRoute(newMatched)
    }
    if (tagList.value.filter(e => e.path === to.fullPath).length === 0 && tagList.value.filter(e => e.name === to.name).length > 0 && (!to.meta.showTag || to.meta.showTag === 1)) {
      keepAliveStore.handleAliveRoute(newMatched)
      scrollPosition.value.forEach(item => {
        if (item.name === to.name) {
          keepAliveStore.removeScrollPosition({ path: item.fullPath })
        }
      })
    }
  }
  // 进度条开启
  if (systemConfig.value && systemConfig.value.isProgressEnable) {
    start()
  }
  // 页面loading开启
  if (systemConfig.value && systemConfig.value.isLoadingEnable) {
    loadStart()
  }
  const externalLink = to?.redirectedFrom?.fullPath
  // 配置页面标题
  if (!externalLink || externalLink === '/' || (externalLink && to.path !== '/Exception/404')) {
    setPageTitle(to.meta)
  }
  if (userInfo.value) {
    window.electronAPI.send('already-login')
    if (_from?.name === 'Login' || !_from?.name) {
      // 如果是从登录页过来的，或者name不存在（说明是浏览器刷新事件），则需要请求路由数据，再执行下一步
      if (menuList.value.length === 0) {
        initRouter().then(() => {
          let routerPath = ''
          if (to.fullPath === '/') {
            if (tagList.value && tagList.value.length > 0) {
              routerPath = tagList.value[0].path
            } else {
              const remainingRouterName: any = []
              remainingRouter.forEach(item => {
                remainingRouterName.push(item.name)
              })
              const rootRouter = cloneDeep(router.options.routes)
              const rootArr = rootRouter.filter(v => {
                return v.name !== 'Layout' && !remainingRouterName.includes(v.name)
              })
              const index = router.options.routes.findIndex(v => v.name === 'Layout')
              if (router.options.routes[index].children && router.options.routes[index].children.length > 0) {
                routerPath = router.options.routes[index].children[0].path
              } else {
                if (rootArr.length > 0) {
                  routerPath = rootArr[0].path
                } else {
                  routerPath = '/Exception/403'
                }
              }
            }
          } else {
            routerPath = to.path
          }
          // 解决动态获取的路由在页面刷新时控制台会报警告问题
          if (to.path === '/Exception/404' && to.redirectedFrom !== undefined) {
            next({ path: to.redirectedFrom?.fullPath, query: to.redirectedFrom?.query, replace: true })
          } else {
            // router.push(routerPath)
            if (to.path === routerPath && to.name) {
              next()
            } else {
              next({ path: routerPath, query: to.query, replace: true })
            }
          }
        })
      } else {
        if (to.name) {
          tagCacheStore.dynamicRouteTag(to)
        }
        next()
      }
    } else {
      // 如果是其他页面跳转的，且其他页面的name存在，则再判断当前跳转页是否是外链页面
      if (externalLink && externalLink.includes('http')) {
        if (systemConfig.value && systemConfig.value.isProgressEnable) {
          done()
        }
        if (systemConfig.value && systemConfig.value.isLoadingEnable) {
          loadDone()
        }
        openLink(`http${split(externalLink, 'http')[1]}`)
      } else {
        tagCacheStore.dynamicRouteTag(to)
        let routerPath = ''
        if (to.fullPath === '/') {
          if (tagList.value && tagList.value.length > 0) {
            routerPath = tagList.value[0].path
          } else {
            const remainingRouterName: any = []
            remainingRouter.forEach(item => {
              remainingRouterName.push(item.name)
            })
            const rootRouter = cloneDeep(router.options.routes)
            const rootArr = rootRouter.filter(v => {
              return v.name !== 'Layout' && !remainingRouterName.includes(v.name)
            })
            const index = router.options.routes.findIndex(v => v.name === 'Layout')
            if (router.options.routes[index].children && router.options.routes[index].children.length > 0) {
              routerPath = router.options.routes[index].children[0].path
            } else {
              if (rootArr.length > 0) {
                routerPath = rootArr[0].path
              } else {
                routerPath = '/Exception/403'
              }
            }
          }
          next({ path: routerPath, replace: true })
        } else {
          next()
        }
      }
    }
  } else {
    window.electronAPI.send('need-login')
    // 未登录
    // 当前访问页面包含在路由白名单中，可直接跳转
    if (routerWhiteList.login.includes(to.name as string)) {
      next()
    } else {
      // 当前访问页面需要登录才能访问，需先跳转到登陆页，并将当前访问路由通过链接保存，在登陆后，获取该路由进行跳转
      next(`/Login?redirect=${to.fullPath}`)
    }
  }
})

router.afterEach(() => {
  const { systemConfig } = storeToRefs(appStore)
  if (systemConfig.value && systemConfig.value.isProgressEnable) {
    done()
  }
  if (systemConfig.value && systemConfig.value.isLoadingEnable) {
    loadDone()
  }
})

export const setupRouter = (app: App<Element>) => {
  app.use(router)
}

export default router
